//  @ Project : SPPager
//  @ File Name : HtmlHelperBuilder.cs
//  @ Date : 2013/6/5
//  @ Author : yubaolee(.cpp)
//  @ Description: general html helper

using System;
using System.Collections.Generic;
using System.Web.Mvc;
using System.Text;

namespace LYB.NET.SPPager
{
    public class HtmlHelperBuilder : HelperBase,IBuilder
    {
        public HtmlHelperBuilder(HtmlHelper helper, IPageList pagelist, PageOption pageoption)
            :base(helper, pagelist, pageoption)
        {
           

        }

        public MvcHtmlString RenderPage()
        {
            if ((_pageIndex > _totalPageCount && _totalPageCount > 0) || _pageIndex < 1)
            {
                return
                    MvcHtmlString.Create(string.Format("{0}<div style=\"color:red;font-weight:bold\">{1}</div>",
                    _pageOption.PageIndexOutOfRangeErrorMessage));
            }

            var pageItems = new List<PagerItem>();
            if (_pageOption.ShowFirstLast)
            {
                AddFirst(pageItems);
            }
            if (_pageOption.ShowPreNext)
            {
                AddPrevious(pageItems);
            }

            AddPageNumbers(pageItems);

            if (_pageOption.ShowPreNext)
            {
                AddNext(pageItems);
            }
            if (_pageOption.ShowFirstLast)
            {
                AddLast(pageItems);
            }


            var sb = new StringBuilder();
            foreach (PagerItem item in pageItems)
            {
                sb.Append(GeneratePageItem(item));
            }

            if (_pageOption.ShowPageInput)
                sb.Append(BuildGoToPageSection());


            var tb = new TagBuilder("div");
            if (!string.IsNullOrEmpty(_pageOption.Id))
                tb.GenerateId(_pageOption.Id);
            if (!string.IsNullOrEmpty(_pageOption.CssClass))
                tb.AddCssClass(_pageOption.CssClass);

            tb.InnerHtml = sb.ToString();

            return MvcHtmlString.Create(GoToPageScript + tb.ToString(TagRenderMode.Normal));

        }

        private MvcHtmlString GeneratePageItem(PagerItem item)
        {
            //pager item link
            string url = GenerateURL(item.PageIndex);
            if (item.Disabled) //first,last,next or previous page
                return MvcHtmlString.Create(String.Format("<a disabled=\"disabled\">{0}</a>", item.Text));
            return MvcHtmlString.Create(string.IsNullOrEmpty(url)? _htmlHelper.Encode(item.Text) 
                                                                  : String.Format(" <a href='{0}'>{1}</a> ", url, item.Text));
        }

        private string GenerateAnchor(PagerItem item)
        {
            string url = GenerateURL(item.PageIndex);
            var tag = new TagBuilder("a") { InnerHtml = item.Text };
            tag.MergeAttribute("href", url);
            return string.IsNullOrEmpty(url)
                ? _htmlHelper.Encode(item.Text) : " " + tag.ToString(TagRenderMode.Normal) + " ";
        }

        //generate go to 
        private string BuildGoToPageSection()
        {
            const string ctrlIndexName = "_LYBPager_ControlIndex";
            ViewContext viewCtx = _htmlHelper.ViewContext;
            int ctrlIndex;
            if (int.TryParse((string)viewCtx.HttpContext.Items[ctrlIndexName], out ctrlIndex))
                ++ctrlIndex;
            viewCtx.HttpContext.Items[ctrlIndexName] = ctrlIndex.ToString();

            if (ctrlIndex == 0)
            {
               GoToPageScript =  GoToPageScript.Replace("%InvalidPageIndexErrorMessage%",
                                       _pageOption.InvalidPageIndexErrorMessage).Replace("%PageIndexOutOfRangeErrorMessage%",
                                       _pageOption.PageIndexOutOfRangeErrorMessage);
            }

            string controlId = "_LYBPager_Ctrl" + ctrlIndex;
            string scriptLink = GenerateAnchor(new PagerItem("0", 0, false, PagerItemType.NumericPage));

            string onChangeScript = " onchange=\"_LYBPage_GoToPage(this," + _totalPageCount + ")\"";
            var piBuilder = new StringBuilder();
            piBuilder.AppendFormat(
                    "<input type=\"text\" id=\"{0}\" value=\"{1}\" {2} />",
                    controlId + "_pib", _pageIndex, onChangeScript);

            piBuilder.AppendFormat(
                   "<input type=\"button\" value=\"{0}\" onclick=\"_LYBPage_GoToPage(document.getElementById('{1}')," + _totalPageCount + ")\"/>",
                   "GO"
                   , controlId + "_pib");

            piBuilder.AppendFormat("<span id=\"{0}\" style=\"display:none;width:0px;height:0px\">{1}</span>",
                                  controlId + "_piblink", scriptLink);
            return piBuilder.ToString();
        }

    }
}

